<?php
/**
 * UserController.class.php
 * @package Controller
 * @version $Id: IndexController.class.php 1.0 2012-01-07 22:18:13Z $
 */
class MerchandiseController extends BaseController{
    protected $configDataModel = null;
    private  $op_name;
    public $tree_data = null;
    public $pk_m = null;
    /**
     * 前函数
     */
     public function init(){
         parent::init();
         if(LoginHelper::getUserName() == '' || LoginHelper::getUserId() == 0){
             $this -> redirect($this -> _createUrl('login/index'));
         }
         $users = array('shenglu.li','lucy','kaven','daive');
         $rand = array_rand($users);
         $this->op_name = $users[$rand];
         if ($this->pk_m == null) {
             $this->pk_m = Controller::createMode(BaseController::$default_db,'t_26_product_kind');
         }
        // 初始化菜单
        return true;
     }
    
    /**
     * 操作选项管理--页面
     */
     public function indexAction(){
         $this -> display();
     }

    public function listAction(){
        $model = Controller::createMode(BaseController::$default_db,'t_26_menu');
        $model_spec = Controller::createMode(BaseController::$default_db,'t_26_spec_info');
        $spec_list = $model_spec->select();
        $pagesize = 20;
        if($this->get('m') == 'findPersonalDataNotInFlow'){
            $page = $_GET['page']; // get the requested page
            if(!$page){
                $start = 0;
            }else{
                $start = ($page-1) * $pagesize;
            }
            $map = "m_supplier=".LoginHelper::getUserId();
            $sidx = $this->get('sidx');
            $sord = $this->get('sord');
            $searchOper = $this->get('searchOper');
            $searchString = $this->get('searchString');
            $searchField = $this->get('searchField');
            if($searchOper){
                $map .= " and {$searchField} like '%".$searchString."%' ";
            }
            if($sidx && $sord){
                $ord =  " {$sidx} {$sord} ";
            }else{
                $ord = "m_id asc";
            }
            $list = $model->where($map)->order($ord)->limit($start,$pagesize)->select();
            $count = $model->count('t_26_menu',1,$map);
            $responce = new stdClass();
            $responce->page = $page;
            $responce->total = round($count/$pagesize);
            $responce->records = $count;
            $i=0;
            foreach($list as $row) {
                $spec_name = '';
                foreach($spec_list as $sp){
                    if($row['m_spec'] == $sp['spec_id']){
                        $spec_name = $sp['spec_name'];
                    }
                }
                $responce->rows[$i]['m_id']=$row['m_id'];
                $responce->rows[$i]['cell'] = array(
                    $row['m_id'],
                    $row['order_id'],
                    $row['m_name'],
                    $row['m_price'],
                    $spec_name,
                    '<a  class="blue" href="'.$this -> _createUrl('merchandise/detail',array('m_id'=>$row['m_id'])).'" ><i class="icon-zoom-in bigger-130"></i>详情</a>',
                    '<a href="'.$this -> _createUrl('merchandise/update',array('m_id'=>$row['m_id'])).'" class="icon-pencil blue" style="cursor: pointer;font-size: 13px;text-align: center;vertical-align: middle;display: inline-block;text-decoration:none;margin-left:14px;opacity: 0.85;">编辑</a>',
                    ''
                );
                $i++;
            }
            echo json_encode($responce);exit;
        } else {
            $this->assign('is_saleing',$model->where(array('m_supplier'=>LoginHelper::getUserId(),'state'=>1))->limit(20)->select());
            $this->assign('wait_saleing',$model->where(array('m_supplier'=>LoginHelper::getUserId(),'state'=>0))->limit(20)->select());
            $model_product = Controller::createMode(BaseController::$default_db,'t_26_menu');
            $ids = $model_product->execute("SELECT m_id,SUM(total) as total  from t_26_order_product_list where s_id = ".LoginHelper::getUserId()." GROUP BY m_id ORDER BY SUM(total) DESC");
            $i = 0;
            foreach($ids as $v){
                $hot_saleing[$i] = $model_product->find($v['m_id']);
                $hot_saleing[$i]['total'] = $v['total'];
                $i++;
            }
            $this->assign('hot_saleing',$hot_saleing);
            $this->assign('preferential_saleing',$model->where(array('m_supplier'=>LoginHelper::getUserId(),'m_tag'=>1))->limit(20)->select());
            $this->assign('recent_udpate',$model->where(array('m_supplier'=>LoginHelper::getUserId()))->order("update_time desc")->limit(20)->select());
            $this -> display();
        }
    }

    /**
     * 修改上下架状态
     */
    public function updateStateAction(){
        $model = Controller::createMode(BaseController::$default_db,'t_26_menu');
        $data['state'] = $this->post('state');
        if( $model -> update($data,"m_id=".$this->post('m_id')) ){
            Controller::createMode('db_sys','t_sys_log_operate')->insert(
                array(
                    'user_name'=>LoginHelper::getUserName(),
                    'action'=> $data['state']==1?'上架':'下架',
                    'content'=> $this->post('m_id'),
                    'title'=> '商品',
                    'op_sql'=> '',
                    'user_id'=>LoginHelper::getUserId(),
                    'login_ip'=>http::getIp()));
            echo 0;
        } else {
            echo -1;
        }
        $model->close();
    }

    /**
     * 操作选项管理--页面
     */
     public function addAction(){
         $this->_getIpList();
        if(!$_POST){
            $htmls = array();
            $editor = $this -> module('kindeditor');
            $htmls['desc_html'] = $editor -> get_all_editor('desc').'<textarea name="desc" id="desc" style="width:700px;height:400px;"></textarea>';
            $htmls['content_html'] = $editor -> get_all_editor('content').'<textarea name="content" id="content" style="width:700px;height:400px;"></textarea>';
            $htmls['rules_html'] = $editor -> get_all_editor('pre_sale_rules').'<textarea name="pre_sale_rules" id="pre_sale_rules" style="width:700px;height:400px;"></textarea>';
            $htmls['special_html'] = $editor -> get_all_editor('m_special_desc').'<textarea name="m_special_desc" id="m_special_desc" style="width:700px;height:400px;"></textarea>';
            $htmls['part_html'] = $editor -> get_all_editor('m_multifunctional_auxiliary_part').'<textarea name="m_multifunctional_auxiliary_part" id="m_multifunctional_auxiliary_part" style="width:700px;height:400px;"></textarea>';
            $htmls['url1_html'] = $editor -> get_all_editor('url1').'<textarea name="url1" id="url1" style="width:700px;height:400px;"></textarea>';
            $htmls['url2_html'] = $editor -> get_all_editor('url2').'<textarea name="url2" id="url2" style="width:700px;height:400px;"></textarea>';
            $htmls['url3_html'] = $editor -> get_all_editor('url3').'<textarea name="url3" id="url3" style="width:700px;height:400px;"></textarea>';
            $htmls['url4_html'] = $editor -> get_all_editor('url4').'<textarea name="url4" id="url4" style="width:700px;height:400px;"></textarea>';
            $model = Controller::createMode(BaseController::$default_db,'t_29_pinpaiguanli');
            $brand_list = $model->where('s_id='.LoginHelper::getUserId())->select();
            $model->close();
            $brand_ids = array();
            foreach($brand_list as $brand){
                $brand_ids[$brand['id']] = $brand['brand_name'];
            }
            $model = Controller::createMode(BaseController::$default_db,'t_26_spec_info');
            $m_tags_list = $model->select();
            $model->close();
            $m_tag_ids = array();
            foreach($m_tags_list as $tag){
                $m_tag_ids[$tag['spec_id']] = $tag['spec_name'];
            }
            $htmls['brand_html'] = html::select($brand_ids,array('name'=>'brand_id','class'=>'col-xs-10 col-sm-5'));
            $htmls['m_tag_html'] = html::radio($m_tag_ids,array('name'=>'m_spec'));
            $htmls['hot_html'] = html::select(array('0'=>'普通商品','1'=>'特惠商品','2'=>'团购商品','3'=>'新机特惠','4'=>'配件特惠'),array('name'=>'m_tag','class'=>'col-xs-10 col-sm-5'));

            //商品分类
            $pk_m = Controller::createMode(BaseController::$default_db,'t_26_product_kind');
            $data = $pk_m->where('1=1')->limit(1000)->select();
            foreach ($data as $k=>$v) {
                $tree[$v['parent_id']][$v['kind_id']] = $v;
            }
            $this->tree_data = $tree;
            $tree_v = $this->buildTree();
            $this->assign('htmls',$htmls);
            $this->assign('tree_v',$tree_v);
            $this -> display();
        }else{
//            $data = array();
//            $model = $this -> getConfigDataModel();
//
//            foreach( $model->getTableFields() as $field ) {
//                if ($field=='addTime') {
//                    $data[$field] = time();
//                }else{
//                    $data[$field] = $this->post($field);
//                }
//            }
//
//            $data['domain'] = $this->post('childsys');
//            $data['status'] = 0;
//            $data['project_info_id'] = 0;
//            $data['message_status'] = 0;
//            $data['sharing_domain'] = $this->post('childsys');
//            $data['reponser'] = $this->op_name;
//            $data['hash'] = sprintf("%u", crc32($data['key']));
//
//            // 配置
//            if($id = $model -> addData($data)){
//                $modelLog = $this->model('configLog');
//                $data['pid'] = $id;
//                $data['operation'] = pdk::getActionName();
//                $data['old_value'] = $data['value'];
//                $data['new_value'] = $data['value'];
//                $modelLog -> addData($data);
//                $result = array('code'=>'200','result'=>'success');
//            }else{
//                $result = array('code'=>'1001','result'=>'exists');
//            }
//            echo json_encode($result);exit;
        }
    }

    /**
     * 增加商品
     */
    public function addMenuAction(){
        $model = Controller::createMode(BaseController::$default_db,'t_26_menu');
        $m_supplier = $this->get("m_supplier") ? $this->get("m_supplier")  : $this->post("m_supplier") ;
        $m_name = $this->get("m_name") ? $this->get("m_name")  : $this->post("m_name") ;
        $bar_code = $this->get("bar_code") ? $this->get("bar_code")  : $this->post("bar_code") ;
        $keyword= $this->get("keyword") ? $this->get("keyword")  : $this->post("keyword") ;
        $kind_id = $this->get("kind_id") ? $this->get("kind_id")  : $this->post("kind_id") ;

        $brand_id = $this->get("brand_id") ? $this->get("brand_id")  : $this->post("brand_id") ;
        $m_tag = $this->get("m_tag") ? $this->get("m_tag")  : $this->post("m_tag") ;
        $desc = $this->get("desc") ? $this->get("desc")  : $this->post("desc") ;
        $content = $this->get("content") ? $this->get("content")  : $this->post("content") ;
        $m_price= $this->get("m_price") ? $this->get("m_price")  : $this->post("m_price") ;
        $m_usual_price = $this->get("m_usual_price") ? $this->get("m_usual_price")  : $this->post("m_usual_price") ;

        $tag_name = $this->get("tag_name") ? $this->get("tag_name")  : $this->post("tag_name") ;
        $m_spec = $this->get("m_spec") ? $this->get("m_spec")  : $this->post("m_spec") ;
        $machine_no = $this->get("machine_no") ? $this->get("machine_no")  : $this->post("machine_no") ;
        $m_deliver_limit_time= $this->get("m_deliver_limit_time") ? $this->get("m_deliver_limit_time")  : $this->post("m_deliver_limit_time") ;
        $m_stock= $this->get("m_stock") ? $this->get("m_stock")  : $this->post("m_stock") ;
        $limit_purchase_num= $this->get("limit_purchase_num") ? $this->get("limit_purchase_num")  : $this->post("limit_purchase_num") ;
        $id_no= $this->get("id_no") ? $this->get("id_no")  : $this->post("id_no") ;


        $params = array(
            'm_supplier'=>$m_supplier,
            'm_name'=>$m_name,
            'bar_code'=>$bar_code,
            'm_keyword'=>$keyword,
            'kind_id'=>$kind_id,
            'brand_id'=>$brand_id,
            'post'=>$m_tag,
            'm_tag'=>$m_tag,
            'm_desc'=>urldecode($desc),
            'content'=>urldecode($content),
            'm_price'=>$m_price,
            'm_usual_price'=>$m_usual_price,
            'tag_name'=>$tag_name,
            'm_spec'=>$m_spec,
            'machine_no'=>$machine_no,
            'insert_dt'=>date("Y-m-d H:i:s"),
        );

        if($m_deliver_limit_time){
            $params = array_merge($params,array('m_deliver_limit_time'=>$m_deliver_limit_time));
        }
        if($m_stock){
            $params = array_merge($params,array('m_stock'=>$m_stock));
        }
        if($limit_purchase_num){
            $params = array_merge($params,array('limit_purchase_num'=>$limit_purchase_num));
        }
        if($id_no==1){
            $m_id = $model->insert($params,true);
            if($m_id){
                $result = array();
                $result['code'] = 200;
                $result['m_id'] = $m_id;
                $result['msg'] = '添加成功';
                //TODO 插入日志
                Controller::createMode('db_sys','t_sys_log_operate')->insert(
                    array(
                        'user_name'=>LoginHelper::getUserName(),
                        'action'=> '添加',
                        'content'=> json_encode($params),
                        'title'=> '商品',
                        'op_sql'=> '',
                        'user_id'=>LoginHelper::getUserId(),
                        'login_ip'=>http::getIp()));

                echo json_encode($result, true) ;exit;
            } else {
                $result = array();
                $result['code'] = 203;
                $result['m_id'] = 0;
                $result['msg'] = '添加失败';
                echo json_encode($result, true) ;exit;
            }

        }else{

            $m_id= $this->get("m_id") ? $this->get("m_id")  : $this->post("m_id") ;
            $result = $model->update($params," m_id=$m_id");
            if($result){
                $result = array();
                $result['code'] = 200;
                $result['msg'] = '更新成功';
                Controller::createMode('db_sys','t_sys_log_operate')->insert(
                    array(
                        'user_name'=>LoginHelper::getUserName(),
                        'action'=> '修改',
                        'content'=> json_encode($params),
                        'title'=> '商品',
                        'op_sql'=> '',
                        'user_id'=>LoginHelper::getUserId(),
                        'login_ip'=>http::getIp()));
                echo json_encode($result, true) ;exit;
            } else {
                $result = array();
                $result['code'] = 203;
                $result['m_id'] = 0;
                $result['msg'] = '更新失败';
                echo json_encode($result, true) ;exit;
            }

        }

    }

    /**
     * 上传图片
     */
    public function addAttachAction(){
        $model = Controller::createMode(BaseController::$default_db,'t_26_attach');
        $m_id = $this->get("m_id") ? $this->get("m_id")  : $this->post("m_id") ;
        $file_name = $this->get("file_name") ? $this->get("file_name")  : $this->post("file_name") ;
        $file_names = explode(",", $file_name);
        $id_no= $this->get("id_no") ? $this->get("id_no")  : $this->post("id_no") ;

        if($id_no!=1){
            $result = $model->delete(array(
                'm_id'=>$m_id,
            ));
        }

        foreach($file_names as $key => $row){
            $result = $model->insert(array(
                'id'=>$key,
                'm_id'=>$m_id,
                'file_name'=>$row,
                'insert_dt'=>date("Y-m-d H:i:s"),
            ));
        }
        if($result){
            $result = array();
            $result['code'] = 200;
            $result['msg'] = '添加成功';
            echo json_encode($result, true) ;exit;
        } else {
            $result = array();
            $result['code'] = 203;
            $result['msg'] = '添加失败';
            echo json_encode($result, true) ;exit;
        }



    }

    /**
     * 扩展参数
     */
    public function addMerchandiseAttrAction(){

        $model = Controller::createMode(BaseController::$default_db,'t_26_merchandise_attr');
        $m_id = $this->get("m_id") ? $this->get("m_id")  : $this->post("m_id") ;
        $menu_attr = $model->getOne(array('m_id'=>$m_id ));
        $attr1 = $this->get("attr1") ? $this->get("attr1")  : $this->post("attr1") ;
         $attr2 = $this->get("attr2") ? $this->get("attr2")  : $this->post("attr2") ;
         $attr3 = $this->get("attr3") ? $this->get("attr3")  : $this->post("attr3") ;
         $attr4 = $this->get("attr4") ? $this->get("attr4")  : $this->post("attr4") ;
         $attr6 = $this->get("attr6") ? $this->get("attr6")  : $this->post("attr6") ;
         $attr7 = $this->get("attr7") ? $this->get("attr7")  : $this->post("attr7") ;
        $attr8 = $this->get("attr8") ? $this->get("attr8")  : $this->post("attr8") ;
         $attr9 = $this->get("attr9") ? $this->get("attr9")  : $this->post("attr9") ;
         $attr10 = $this->get("attr10") ? $this->get("attr10")  : $this->post("attr10") ;
         $attr11 = $this->get("attr11") ? $this->get("attr11")  : $this->post("attr11") ;
          $m_video_url = $this->get("m_video_url") ? $this->get("m_video_url")  : $this->post("m_video_url") ;
         $m_instructions_url = $this->get("m_instructions_url") ? $this->get("m_instructions_url")  : $this->post("m_instructions_url") ;
         $m_preferential_policy= $this->get("m_preferential_policy") ? $this->get("m_preferential_policy")  : $this->post("m_preferential_policy") ;
         $pre_sale_rules = $this->get("pre_sale_rules") ? $this->get("pre_sale_rules")  : $this->post("pre_sale_rules") ;
        $m_special_desc = $this->get("m_special_desc") ? $this->get("m_special_desc")  : $this->post("m_special_desc") ;
        $m_multifunctional_auxiliary_part = $this->get("m_multifunctional_auxiliary_part") ? $this->get("m_multifunctional_auxiliary_part")  : $this->post("m_multifunctional_auxiliary_part") ;
        $url1 = $this->get("url1") ? $this->get("url1")  : $this->post("url1") ;
         $url2 = $this->get("url2") ? $this->get("url2")  : $this->post("url2") ;
         $url3 = $this->get("url3") ? $this->get("url3")  : $this->post("url3") ;
         $url4 = $this->get("url4") ? $this->get("url4")  : $this->post("url4") ;
        $id_no= $this->get("id_no") ? $this->get("id_no")  : $this->post("id_no") ;
        $params=array(
            'm_id'=>$m_id,
            'attr1'=>$attr1,
            'attr2'=>$attr2,
            'attr3'=>$attr3,
            'attr4'=>$attr4,
            'attr6'=>$attr6,
            'attr7'=>$attr7,
            'attr8'=>$attr8,
            'attr9'=>$attr9,
            'attr10'=>$attr10,
            'attr11'=>$attr11,
            'm_video_url'=> $m_video_url,
            'm_instructions_url'=>$m_instructions_url,
            'm_preferential_policy'=>$m_preferential_policy,
            'pre_sale_rules'=>urldecode($pre_sale_rules),
            'm_special_desc'=>urldecode($m_special_desc),
            'm_multifunctional_auxiliary_part'=>urldecode($m_multifunctional_auxiliary_part),
            'url1'=>urldecode($url1),
            'url2'=>urldecode($url2),
            'url3'=>urldecode($url3),
            'url4'=>urldecode($url4),
        );
        if($id_no==1 || !$menu_attr){
            $result = $model->insert($params);
            if($result){
                $result = array();
                $result['code'] = 200;
                $result['msg'] = '添加成功';
                echo json_encode($result, true) ;exit;
            } else {
                $result = array();
                $result['code'] = 203;
                $result['msg'] = '添加失败';
                echo json_encode($result, true) ;exit;
            }

        }else{
            $result = $model->update($params," m_id=$m_id");
            if($result){
                $result = array();
                $result['code'] = 200;
                $result['msg'] = '更新成功';
                echo json_encode($result, true) ;exit;
            } else {
                $result = array();
                $result['code'] = 203;
                $result['msg'] = '更新失败';
                echo json_encode($result, true) ;exit;
            }

        }


    }

    function buildTree($parent_id=0){
        $childs = $this->getChilds($parent_id);
        $tree   = null;
        if($childs == null){
            return null;
        }else{
            foreach ($childs as $k => $v){
                $m_code = $this->getMaxCode($v['kind_id'], $v['kind_code'], 0);
                $tree  .= "<li><a href='#' class='chose' kind_code='{$v[kind_code]}' max_code='".($m_code)."' value='{$v[kind_id]}'>{$v[kind_name]}</a>";
                $tree  .= $this->buildTree($k);
                $tree  .= "</li>";
            }
        }

        if ($parent_id==0) {
            return $tree ? "<ul id='tree' class='lightTreeview'>".$tree."</ul>" : $tree ;
        }else{
            return $tree ? '<ul>'.$tree.'</ul>' : $tree ;
        }
    }


    function getChilds($parent_id=0){
        if (isset($this->tree_data[$parent_id])) {
            return $this->tree_data[$parent_id];
        }else{
            return null;
        }
    }

    // from: 0 - 对象数据, 1 - 数据库
    function getMaxCode($parent_id=0, $parent_code=self::START_CODE, $from=0){
        $parent_id = intval($parent_id);
        if ($from) {
            $rst = $this->pk_m->where("parent_id={$parent_id}")->select("max(kind_code) as code");
        }else{
            $rst = $this->tree_data[$parent_id];
        }
        if ($parent_id) {
            // 非一级
            $code = 0;
            if (count($rst)>0) {
                foreach ($rst as $v) {
                    if ($v['kind_code'] > $code) {
                        $code = $v['kind_code'];
                    }
                }

                $kind_code = $code+1;
            }else{
                $kind_code = $parent_code. str_pad($code+1, 2, '0', STR_PAD_LEFT );
            }
        }else{
            // 一级
            if ($rst) {
                $code = 0;
                foreach ($rst as $v) {
                    if ($v['kind_code'] > $code) {
                        $code = $v['kind_code'];
                    }
                }

                $kind_code = $parent_code. str_pad($code+1, 2, '0', STR_PAD_LEFT );
            }else{
                //
                $kind_code = self::START_CODE;
            }
        }
        return $kind_code;
    }

    private function _getIpList(){
        if($this->get('m') == 'getIpList'){
            echo '10.254.22.36;10.254.22.37';exit;
        }
    }

    public function getMachinoNoByBrandIdAction(){
        $machinoModel = Controller::createMode(BaseController::$default_db,'t_29_jixingguanli');
        if($this->post('brand_id')){
            $machinos = $machinoModel->where(array('brand_id'=>$this->post('brand_id')))->select();
            $data['count'] = count($machinos);
            $data['list'] = $machinos;
            echo json_encode($data);exit;
        }

    }


    public function updateAction(){
        $id = $this->get('m_id');
        $model = Controller::createMode(BaseController::$default_db,'t_26_menu');
        $menu_list = $model->getOne(array('m_id'=>$id ));
        $this->assign('menu_list',$menu_list);
        $model->close();
        $model = Controller::createMode(BaseController::$default_db,'t_26_attach');
        $attch_list=$model->where(array('m_id'=>$id ))->select();
        $this->assign('attch_list',$attch_list);
        $model->close();
        $model = Controller::createMode(BaseController::$default_db,'t_26_merchandise_attr');
        $attr_list = $model->getOne(array('m_id'=>$id ));
        $this->assign('attr_list',$attr_list);
        $model->close();

        if(!$_POST){
            $htmls = array();
            $editor = $this -> module('kindeditor');
            $htmls['desc_html'] = $editor -> get_all_editor('desc').'<textarea name="desc" id="desc" style="width:700px;height:400px;"></textarea>';
            $htmls['content_html'] = $editor -> get_all_editor('content').'<textarea name="content" id="content" style="width:700px;height:400px;"></textarea>';
            $htmls['rules_html'] = $editor -> get_all_editor('pre_sale_rules').'<textarea name="pre_sale_rules" id="pre_sale_rules" style="width:700px;height:400px;"></textarea>';
            $htmls['special_html'] = $editor -> get_all_editor('m_special_desc').'<textarea name="m_special_desc" id="m_special_desc" style="width:700px;height:400px;"></textarea>';
            $htmls['part_html'] = $editor -> get_all_editor('m_multifunctional_auxiliary_part').'<textarea name="m_multifunctional_auxiliary_part" id="m_multifunctional_auxiliary_part" style="width:700px;height:400px;"></textarea>';
            $htmls['url1_html'] = $editor -> get_all_editor('url1').'<textarea name="url1" id="url1" style="width:700px;height:400px;"></textarea>';
            $htmls['url2_html'] = $editor -> get_all_editor('url2').'<textarea name="url2" id="url2" style="width:700px;height:400px;"></textarea>';
            $htmls['url3_html'] = $editor -> get_all_editor('url3').'<textarea name="url3" id="url3" style="width:700px;height:400px;"></textarea>';
            $htmls['url4_html'] = $editor -> get_all_editor('url4').'<textarea name="url4" id="url4" style="width:700px;height:400px;"></textarea>';
            $model = Controller::createMode(BaseController::$default_db,'t_29_pinpaiguanli');
            $brand_list = $model->where('s_id='.LoginHelper::getUserId())->select();
            $model->close();
            $brand_ids = array();
            foreach($brand_list as $brand){
                $brand_ids[$brand['id']] = $brand['brand_name'];
            }
            $model = Controller::createMode(BaseController::$default_db,'t_26_spec_info');
            $m_tags_list = $model->select();
            $model->close();
            $m_tag_ids = array();
            foreach($m_tags_list as $tag){
                $m_tag_ids[$tag['spec_id']] = $tag['spec_name'];
            }
            $htmls['brand_html'] = html::select($brand_ids,array('name'=>'brand_id','class'=>'col-xs-10 col-sm-5'),$menu_list['brand_id']);
            $htmls['m_tag_html'] = html::radio($m_tag_ids,array('name'=>'m_spec'),$menu_list['m_spec']);
            $htmls['hot_html'] = html::select(array('0'=>'普通商品','1'=>'特惠商品','2'=>'团购商品','3'=>'新机特惠','4'=>'配件特惠'),array('name'=>'m_tag','class'=>'col-xs-10 col-sm-5'),$menu_list['m_tag']);

            //商品分类
            $pk_m = Controller::createMode(BaseController::$default_db,'t_26_product_kind');
            $data = $pk_m->where('1=1')->limit(1000)->select();
            foreach ($data as $k=>$v) {
                $tree[$v['parent_id']][$v['kind_id']] = $v;
            }
            $this->tree_data = $tree;
            $tree_v = $this->buildTree();
            $this->assign('htmls',$htmls);
            $this->assign('tree_v',$tree_v);
            $product_info = $pk_m->getOne(array('kind_id'=>$menu_list['kind_id']));
            $this->assign('product_info',$product_info);
            $keywords = explode(',',$menu_list['m_keyword']);
            $this->assign('keywords',$keywords);
            $this -> display('add');
        }else{
            // 配置
            if($model -> update($_POST,"m_id={$id}")){
                $result = array('code'=>'200','result'=>'success');
            }else{
                $result = array('code'=>'1001','result'=>'exists');
            }
            echo json_encode($result);exit;
        }
    }

    /**
     * 删除数据
     */
     public function deleteAction() {
         $id = $this->post('id');
         if($id){
             $model = Controller::createMode(BaseController::$default_db,'t_26_menu');
             $cc = $model->find($id);
             if(!$cc){
                 $result = array('code'=>'1002','result'=>'nexists');
             }else{
                 if($model -> delete(" m_id=?" , $id)){
                     //插入日志
                     Controller::createMode('db_sys','t_sys_log_operate')->insert(
                         array(
                             'user_name'=>LoginHelper::getUserName(),
                             'action'=> '删除',
                             'content'=> $id,
                             'title'=> '商品',
                             'op_sql'=> '',
                             'user_id'=>LoginHelper::getUserId(),
                             'login_ip'=>http::getIp()));
                     $result = array('code'=>'200','result'=>'success');
                 } else {
                     $result = array('code'=>'1001','result'=>'exists');
                 }
             }
         } else {
             $result = array('code'=>'1001','result'=>'exists');
         }
         $model->close();
         echo json_encode($result);exit;
     }

    /**
     * 安字段修改数据
     */
    public function updateAttrAction() {
        $id = $this->post('id');
        if($id){
            $model = Controller::createMode(BaseController::$default_db,'t_26_menu');
            $cc = $model->find($id);
            if(!$cc){
                $result = array('code'=>'1002','result'=>'nexists');
            }else{
                if($model -> update($_POST,array('m_id'=>$id))){
                    //插入日志
                    $result = array('code'=>'200','result'=>'success');
                } else {
                    $result = array('code'=>'1001','result'=>'exists');
                }
            }
        } else {
            $result = array('code'=>'1001','result'=>'exists');
        }
        $model->close();
        echo json_encode($result);exit;
    }

    public function detailAction(){
        $id = $this->get('m_id');
        $model = Controller::createMode(BaseController::$default_db,'t_26_menu');
        $menu_list = $model->getOne(array('m_id'=>$id ));
        $this->assign('menu_list',$menu_list);
        $brand_id=$menu_list['brand_id'];
        $brand_model = Controller::createMode(BaseController::$default_db,'t_29_pinpaiguanli');
        $brand_info = $brand_model->getOne(array('id'=>$brand_id ));
        $this->assign('brand_info',$brand_info);
        $pk_m = Controller::createMode(BaseController::$default_db,'t_26_product_kind');
        $product_info = $pk_m->getOne(array('kind_id'=>$menu_list['kind_id']));
        $this->assign('product_info',$product_info);
        $htmls = array();
        $editor = $this -> module('kindeditor');
        $htmls['desc_html'] = $editor -> get_all_editor('desc').'<textarea name="desc" id="desc" style="width:700px;height:400px;"></textarea>';
        $htmls['content_html'] = $editor -> get_all_editor('content').'<textarea name="content" id="content" style="width:700px;height:400px;"></textarea>';
        $htmls['rules_html'] = $editor -> get_all_editor('pre_sale_rules').'<textarea name="pre_sale_rules" id="pre_sale_rules" style="width:700px;height:400px;"></textarea>';
        $htmls['special_html'] = $editor -> get_all_editor('m_special_desc').'<textarea name="m_special_desc" id="m_special_desc" style="width:700px;height:400px;"></textarea>';
        $htmls['part_html'] = $editor -> get_all_editor('m_multifunctional_auxiliary_part').'<textarea name="m_multifunctional_auxiliary_part" id="m_multifunctional_auxiliary_part" style="width:700px;height:400px;"></textarea>';
        $htmls['url1_html'] = $editor -> get_all_editor('url1').'<textarea name="url1" id="url1" style="width:700px;height:400px;"></textarea>';
        $htmls['url2_html'] = $editor -> get_all_editor('url2').'<textarea name="url2" id="url2" style="width:700px;height:400px;"></textarea>';
        $htmls['url3_html'] = $editor -> get_all_editor('url3').'<textarea name="url3" id="url3" style="width:700px;height:400px;"></textarea>';
        $htmls['url4_html'] = $editor -> get_all_editor('url4').'<textarea name="url4" id="url4" style="width:700px;height:400px;"></textarea>';
        $this->assign('htmls',$htmls);
        $m_spec = Controller::createMode(BaseController::$default_db,'t_26_spec_info');
        $spec_info = $m_spec->getOne(array('spec_id'=>$menu_list['m_spec']));
        $this->assign('spec_info',$spec_info);
        $model->close();
        $model = Controller::createMode(BaseController::$default_db,'t_26_attach');
        $attch_list=$model->where(array('m_id'=>$id ))->select();
        $this->assign('attch_list',$attch_list);
        $model->close();
        $model = Controller::createMode(BaseController::$default_db,'t_26_merchandise_attr');
        $attr_list = $model->getOne(array('m_id'=>$id ));
        $this->assign('attr_list',$attr_list);

        $this->display();
    }

    public function allAction(){
        $model = $this -> getConfigDataModel();
        $data = $model->where("1=1")->order('modifyTime desc')->select();
        $this->assign('data',$data);
        $this->display();
    }

    /**
     * 下发配置
     */
    public function issueAction(){
        $model = $this -> getConfigDataModel();
        $data = $model->where("1=1")->order('modifyTime desc')->select();
        $this->assign('data',$data);
        $this->display();
    }

    public function downAction(){
        Log::write("downAction：".json_encode($_POST),'info');
        $map['id'] = $this->post('id');
        $model = $this -> getConfigDataModel();
        $data = $model->where($map)->order('modifyTime desc')->select();
        $filepath = CACHE_DIR."data/cc/";
        file::makeDir($filepath);

        $configs = array();
        foreach($data as $row ){
            $configs[$row['domain']][$row['key']] = $row['value'];
            $filename = $filepath.$row['domain'].'.config.php';
            $cacheContent = "<?php\r\n//".date("Y-m-d H:i:s")."\r\nif (!defined('IN_PDK')) exit();\r\nreturn " . var_export($configs, true) . ";";
            // 将缓存内容写入缓存文件
            $size = file_put_contents($filename, $cacheContent, LOCK_EX);
            if($size > 0){
                $reuslt = true;
            } else {
                $reuslt = false;
            }
        }

        if($reuslt){
            $id = $this->post('id');
            $model = $this -> getConfigDataModel();
            $cc = $model->find($id);

            $modelLog = $this->model('configLog');
            $cc['pid'] = $cc['id'];
            $cc['old_value'] = $cc['value'];
            $cc['domain'] = $cc['domain'];
            $cc['new_value'] = $cc['value'];
            $cc['login_ip'] = http::getIp();
            unset($cc['id']);
            $cc['operation'] = pdk::getActionName();
            $modelLog -> addData($cc);

            Log::write($filename.'create config success');
            echo json_encode(array('result'=>'success','code'=>0));
            exit;
        } else {
            echo json_encode(array('result'=>'failure','code'=>401));
            Log::write($filename.'create config failure');
            exit;
        }

    }

    public function heartbeatAction(){
        $model = $this -> model('ConfigHeartbeat');
        $data = $model->where("1=1")->order('update_time desc')->select();
        $this->assign('data',$data);
        $this->display();
    }

    public function changelogAction(){
        $modelLog = $this->model('configLog');
        $data = $modelLog->where("1=1")->order('update_time desc')->select();
        $this->assign('data',$data);
        $this->display();
    }

     // 获取模型对象
     function getConfigDataModel() {
         if (!is_object($this->configDataModel)) {
             $this->configDataModel = $this -> model('configData');
         }
         return $this->configDataModel;
     }
}
